package com.cars.theadpool.executor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 打印线程池情况
 *
 * @author: caoqianfan
 * @date: 2023/11/13 10:21
 */
@Slf4j
//1、继承ThreadPoolTaskExecutor
public class VisibleThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {


    //2、编写打印线程池方法
    private void log(String method) {
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();

        log.info("线程池：{}, 执行方法：{},任务数量 [{}], 完成任务数量 [{}], 活跃线程数 [{}], 队列长度 [{}]",
                this.getThreadNamePrefix(),
                method,
                threadPoolExecutor.getTaskCount(),
                threadPoolExecutor.getCompletedTaskCount(),
                threadPoolExecutor.getActiveCount(),
                threadPoolExecutor.getQueue().size());
    }


    //3、重写方法，进行日志的记录
    @Override
    public void execute(Runnable task) {
        log("execute");
        super.execute(task);
    }

    @Override
    public Future<?> submit(Runnable task) {
        log("submit");
        return super.submit(task);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        log("submit");
        return super.submit(task);
    }
}